package com.ldu.exam.assistant;

import java.beans.FeatureDescriptor;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class BeanAssistant 
{
	public static String[] getNullPropertyNames( Object source, String... ignoreProperties ) 
	{
	    final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
	    return Stream.of(wrappedSource.getPropertyDescriptors())
	            .map(FeatureDescriptor::getName)
	            .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null || Arrays.asList(ignoreProperties).contains(propertyName))
	            .toArray(String[]::new);
	}
	
	
	public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) 
	{    
		Map<Object, Boolean> seen = new ConcurrentHashMap<>();    
		return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
	}

}
